<template>
  <div class="contract-create">
    <el-steps :active="currentStep" simple>
      <el-step title="选择模版" icon="el-icon-document"></el-step>
      <el-step title="填写控件" icon="el-icon-edit-outline"></el-step>
      <el-step title="预览合同" icon="el-icon-picture"></el-step>
      <el-step title="完成" icon="el-icon-finished"></el-step>
    </el-steps>
    <div class="steps-content">
      <!-- 选择模版 -->
      <div v-if="currentStep === 0" class="steps-content-align">
        <el-form ref="stepOneForm" :model="stepOneForm" :rules="stepOneRules" label-width="120px" label-position="left">
          <el-form-item label="选择模版" prop="templateId" required>
            <el-select v-model="stepOneForm.templateId" placeholder="请选择模板">
              <el-option
                v-for="temp in templateList"
                :key="temp.TemplateId"
                :label="temp.TemplateName"
                :value="temp.TemplateId"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="签署截止日期" prop="deadline" required>
            <el-date-picker
              type="date"
              placeholder="选择日期"
              :picker-options="pickerOptions"
              value-format="timestamp"
              v-model="stepOneForm.deadline"
              style="width: 260px"
            ></el-date-picker>
          </el-form-item>
          <!-- 劳务派遣合同 -->
          <template v-if="templateType === 1">
            <el-form-item label="经办人" prop="agentName" required>
              <el-input v-model="stepOneForm.agentName"></el-input>
            </el-form-item>
            <el-form-item label="经办手机号" prop="agentMobile" required>
              <el-input v-model="stepOneForm.agentMobile"></el-input>
            </el-form-item>
          </template>
          <!-- 劳动合同 -->
          <template v-if="templateType === 2">
            <div style="margin: 30px 0">将对以下{{ workerList.length }}人发起劳动合同：</div>
            <el-table :data="workerList" element-loading-text="加载中" border fit highlight-current-row>
              <el-table-column label="姓名" min-width="120" :show-overflow-tooltip="true" align="center">
                <template slot-scope="scope">
                  {{ scope.row.name }}
                </template>
              </el-table-column>
              <el-table-column label="手机号" min-width="120" :show-overflow-tooltip="true" align="center">
                <template slot-scope="scope">
                  <span>{{ scope.row.mobile }}</span>
                </template>
              </el-table-column>
              <el-table-column label="身份证号" min-width="120" :show-overflow-tooltip="true" align="center">
                <template slot-scope="scope">
                  {{ scope.row.idcardNo }}
                </template>
              </el-table-column>
            </el-table>
          </template>
          <el-form-item class="form-btns">
            <!-- <el-button @click="cancelForm('agreementForm')">取消</el-button> -->
            <el-button type="primary" @click="nextStep('stepOneForm', 1)">下一步</el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 填写控件 -->
      <div v-if="currentStep === 1">
        <el-form v-if="dynamicControlsArr.length" ref="stepTwoForm" :model="stepTwoForm" label-width="120px" label-position="left">
          <div v-for="item in dynamicControlsArr" :key="item.ChannelComponentId">
            <el-form-item :label="item.ComponentDescription" :prop="item.ComponentName" :required="item.ComponentRequired">
              <!-- 文本 TEXT -->
              <el-input v-if="item.ComponentType === 'TEXT'" v-model="stepTwoForm[item.ComponentName]"></el-input>
              <span v-if="item.ComponentName==='monthlypay'" style="marginLeft: 10px">元</span>
              <!-- 日期 DATE -->
              <el-date-picker
                v-if="item.ComponentType === 'DATE'"
                type="date"
                placeholder="选择日期"
                :picker-options="pickerOptions"
                value-format="timestamp"
                v-model="stepTwoForm[item.ComponentName]"
                style="width: 260px"
              ></el-date-picker>
              <!-- 长文本 MULTI_LINE_TEXT -->
              <el-input v-if="item.ComponentType === 'MULTI_LINE_TEXT'" type="textarea" v-model="stepTwoForm[item.ComponentName]" style="width: 260px"></el-input>
            </el-form-item>
          </div>
          <el-form-item class="form-btns">
            <el-button @click="backLastStep(0)">上一步</el-button>
            <el-button type="primary" @click="nextStep('stepTwoForm', 2)" v-loading.lock="previewLoading">下一步</el-button>
          </el-form-item>
        </el-form>
        <div v-else>
          <el-result icon="info" subTitle="当前选择的模版暂无填写控件，请直接进入下一步">
            <template slot="extra">
              <el-button @click="backLastStep(0)">上一步</el-button>
              <el-button type="primary" size="medium" @click="nextStep('', 2)">下一步</el-button>
            </template>
          </el-result>
        </div>
      </div>

      <!-- 预览合同 -->
      <div :class="['contract-preview', {'preview-loading': !createLoading}]" v-if="currentStep === 2">
        <iframe v-if="previewSrc" :src="previewSrc" class="ifram-wrapper"></iframe>
        <el-result v-if="showPreviewError" icon="error" title="合同预览失败" subTitle="请根据返回上一步重新填写并发起">
          <template slot="extra">
            <el-button type="primary" size="medium">返回</el-button>
          </template>
        </el-result>

        <div class="form-btns">
          <el-button @click="backLastStep(0)">重新发起</el-button>
          <el-button type="primary" @click="clickSubmitCreate" v-loading.lock="createLoading">确认发起</el-button>
        </div>
      </div>

      <!-- 完成 -->
      <div v-if="currentStep === 3">
        <el-result icon="success" title="发起合同成功" subTitle="">
          <template slot="extra">
            <el-button type="primary" size="medium" @click="clickFinished">完成</el-button>
          </template>
        </el-result>
        <el-result v-if="showCreateFail" icon="error" title="发起合同失败" subTitle="请重新发起">
          <template slot="extra">
            <el-button type="primary" size="medium" @click="backLastStep(0)">返回</el-button>
          </template>
        </el-result>
      </div>

    </div>
  </div>
</template>

<script>
import moment from 'moment';
import { validMobile, checkIDCard } from '@common/utils/validate';
import { createFlowsByTemplates } from '@common/api/tenant';
import { createContracts } from '@common/api/worker';
import { formatTime } from '@common/utils/time';

export default {
  name: 'contractCreate',
  components: {
  },
  props: {
    templateType: {
      type: Number,
    },
    templateList: {
      type: Array,
      default() {
        return [];
      },
    },
    currentRow: {
      type: Object,
      default() {
        return {};
      },
    },
    close: {
      type: Function,
    },
    workerList: {
      type: Array,
      default() {
        return [];
      },
    },
  },
  watch: {
    currentRow: {
      handler(newVal, oldVal) {
        if (newVal?.enterpriseOperator?.name !== oldVal?.enterpriseOperator?.name) {
          this.$refs?.stepOneForm?.resetFields();
          this.$set(this, 'stepOneForm', {
            agentName: newVal?.enterpriseOperator?.name,
            agentMobile: newVal?.enterpriseOperator?.mobile,
          });
        }
      },
      immediate: true,
      deep: true,
    },
  },
  data() {
    return {
      currentStep: 0,
      stepOneForm: {
        templateId: '',
        deadline: '',
        agentName: '',
        agentMobile: '',
      },
      stepOneRules: {
        templateId: [
          { required: true, message: '请选择模版', trigger: 'change' },
          { required: true, message: '请选择模版', trigger: 'blur' },
        ],
        deadline: [
          { required: true, message: '请选择签署截止日期', trigger: 'change' },
          { required: true, message: '请选择签署截止日期', trigger: 'blur' },
        ],
        agentName: [
          { required: true, message: '请输入经办人', trigger: 'change' },
          { required: true, message: '请输入经办人', trigger: 'blur' },
        ],
        agentMobile: [
          { required: true, message: '请输入经办人手机号', trigger: 'change' },
          { required: true, message: '请输入经办人手机号', trigger: 'blur' },
          { validator: validMobile, message: '请输入正确的手机号' },
        ],
      },
      selectedTemplateData: {},
      dynamicControlsArr: [],
      stepTwoForm: {},
      previewSrc: '',
      previewLoading: false, // 预览loading
      showPreviewError: false,
      createLoading: false,
      showCreateFail: false,
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() < Date.now();
        },
      },
    };
  },
  created() {

  },
  methods: {
    // 重置弹框
    resetCreate() {
      this.currentStep = 0;
      if (this.$refs?.stepOneForm) {
        this.$refs?.stepOneForm?.resetFields();
        this.$set(this, 'stepOneForm', { templateId: '', deadline: '', agentName: '', agentMobile: '' });
      }
    },
    // 下一步
    nextStep(formName, step) {
      if (this.templateType === 2 && this.workerList?.length === 0) { // 劳动合同
        return false;
      }
      if (!formName) {
        // this.currentStep = step;
        this.createToPreview(step);
        return false;
      }
      this.$refs[formName].validate(async valid => {
        if (valid) {
          if (formName === 'stepOneForm') { // 第一步 选择模版
            this.currentStep = step;
            this.formatDynamicControls();
          }
          if (formName === 'stepTwoForm') { // 填写控件
            // 结束时间不能小于开始时间

            this.createToPreview(step);
          }
        }
      });
    },
    // 上一步
    backLastStep(step) {
      this.currentStep = step;
    },

    // 处理用工单位发起流程参数
    handleTenantFlowInfos(data) {
      const curTemplate = this.templateList.filter(f => f.TemplateId === data?.templateId)?.[0] || null;
      // console.log('curTemplate', curTemplate, data);
      let flowInfos = {};
      // BtoB场景
      const flowApprovers = [];
      const enterpriseArr = curTemplate?.Recipients?.filter(f => f.RecipientType === 'ENTERPRISE') || [];
      const formFields = this.dynamicControlsArr?.map(f => ({
        // eslint-disable-next-line no-nested-ternary
        ComponentValue: f.ComponentType === 'DATE'
          ? (data[f.ComponentName] ? (moment(data[f.ComponentName]).format('YYYY年MM月DD日')) : '')
          : `${data[f.ComponentName]}`,
        ComponentName: f.ComponentName,
        ComponentType: f.ComponentType,
      }));
      if (enterpriseArr?.length === 2) {
        enterpriseArr.forEach(item => {
          const signB = {
            ApproverType: 'ORGANIZATION',
            OrganizationName: item.RoleName,
            RecipientId: item.RecipientId,
          };
          // 非发起方 当前场景属于 渠道外企业签署方
          if (!item.IsPromoter) {
            signB.NotChannelOrganization = true; // 声明是渠道外的企业
            signB.OrganizationName = this.currentRow.name; // 企业名称
            signB.Name = data?.agentName;
            signB.Mobile = data?.agentMobile;
          }
          flowApprovers.push(signB);
        });
        flowInfos = {
          FlowName: `${this.currentRow.name}的劳动派遣合同`,
          TemplateId: data?.templateId,
          FlowDescription: `${this.currentRow.name}劳动派遣合同`,
          FlowType: '劳务',
          Deadline: moment(data.deadline).unix(),
          FlowApprovers: flowApprovers,
          FormFields: formFields,
        };
      }
      return flowInfos;
    },

    // 处理工人发起流程参数
    handleWorkerFlowInfos(data) {
      const curTemplate = this.templateList.filter(f => f.TemplateId === data?.templateId)?.[0] || null;
      const formFields = this.dynamicControlsArr?.map(f => ({
        ComponentValue: f.ComponentType === 'DATE' ? moment(data[f.ComponentName]).format('YYYY年MM月DD日') : `${data[f.ComponentName]}`,
        ComponentName: f.ComponentName,
        ComponentType: f.ComponentType,
      }));
      const flowInfos = [];
      let flowApprovers = [];
      // 场景1: BtoC场景 1个C 和 多个C
      const organArr = curTemplate?.Recipients?.filter(f => f.RecipientType === 'ENTERPRISE');
      const organApprover = {
        ApproverType: 'ORGANIZATION',
        OrganizationName: this.orgname,
        RecipientId: organArr[0]?.RecipientId,
        NeedOpenId: true,
      };
      const personArr = curTemplate?.Recipients?.filter(f => f.RecipientType === 'INDIVIDUAL');
      this.workerList.forEach(item => {
        const usersApprover = {
          ApproverType: 'PERSON',
          RecipientId: personArr[0]?.RecipientId,
          Name: item.name,
          Mobile: item.mobile,
          WorkerId: item.id,
        };
        const callback = error => {
          if (!error) {
            usersApprover.IdCardType = 'ID_CARD';
            usersApprover.IdCardNumber = item.idcardNo;
          }
        };
        if (item.idcardNo) {
          // 身份证号有效
          checkIDCard('', item.idcardNo, callback);
        }
        flowApprovers = [organApprover, usersApprover];
        flowInfos.push({
          FlowName: `${item.name}的劳动合同_${formatTime(new Date(), { format: 'YYYY-MM-DD' })}`,
          Deadline: moment(data.deadline).unix(),
          TemplateId: curTemplate?.TemplateId,
          FlowApprovers: flowApprovers,
          FormFields: formFields,
        });
      });
      return flowInfos;
    },

    // 发起合同预览模式
    async createToPreview(step) {
      this.previewLoading = true;
      const formObj = Object.assign(this.stepOneForm, this.stepTwoForm);
      let flowInfos = null;
      if (this.templateType === 1) {
        flowInfos = this.handleTenantFlowInfos(formObj);
      }
      if (this.templateType === 2) { // BtoC劳动合同
        flowInfos = this.handleWorkerFlowInfos(formObj);
      }
      try {
        const params = {
          flowInfos,
          needPreview: true, // 预览模式
          previewType: 1, // 返回h5链接
        };
        if (this.templateType === 1) {
          params.tenantId = this.currentRow.id; // 用工企业id
        }
        const response = await (this.templateType === 2 ? createContracts : createFlowsByTemplates)(params);

        if (response?.code === 20000 && response?.data?.PreviewUrls?.length) {
          this.previewLoading = false;
          this.showPreviewError = false;
          this.previewSrc = response.data.PreviewUrls[0] || '';
          this.currentStep = step; // 拿到合同预览链接，跳转到下一步
        } else {
          this.previewLoading = false;
          this.showPreviewError = true;
          this.currentStep = step;
          this.$message({
            message: '合同预览失败',
            type: 'warning',
          });
        }
      } catch (error) {
        console.log('error====---', error);
        this.previewLoading = false;
        this.showPreviewError = true;
        this.$message({
          message: error || '合同预览失败',
          type: 'warning',
        });
      }
    },

    // 确认发起
    async clickSubmitCreate() {
      const formObj = Object.assign(this.stepOneForm, this.stepTwoForm);
      let flowInfos = null;
      if (this.templateType === 1) {
        flowInfos = this.handleTenantFlowInfos(formObj);
      }
      if (this.templateType === 2) { // BtoC劳动合同
        flowInfos = this.handleWorkerFlowInfos(formObj);
      }
      const params = {
        flowInfos,
        needPreview: false, // 预览模式
      };
      if (this.templateType === 1) {
        params.tenantId = this.currentRow.id; // 用工企业id
      }
      this.createLoading = true;
      try {
        const response = await (this.templateType === 2 ? createContracts : createFlowsByTemplates)(params);
        if (response?.code === 20000) {
          this.createLoading = false;
          this.showCreateFail = false;
          // this.$message({
          //   message: '发起合同成功',
          //   type: 'success',
          // });
          this.currentStep = 3; // 跳转下一步
        } else {
          this.createLoading = false;
          this.showCreateFail = true;
          this.$message({
            message: '发起合同失败',
            type: 'warning',
          });
        }
      } catch (error) {
        console.log('error====---', error);
        this.createLoading = false;
        this.showCreateFail = true;
        this.$message({
          message: error || '发起合同失败',
          type: 'warning',
        });
      }
    },

    // 完成
    clickFinished() {
      this.close();
      // 跳转到待签署页面
      const pathUrl = this.templateType === 2 ? '/worker/waitSign' : '/tenant/init';
      this.$router.push({
        path: pathUrl,
      });
    },

    // 填写控件 去动态拿取模版中的控件
    formatDynamicControls() {
      this.selectedTemplateData = this.templateList.find(f => f.TemplateId === this.stepOneForm.templateId);
      // 模版里里面拿到的控件
      this.dynamicControlsArr = this.selectedTemplateData?.Components;
      if (this.dynamicControlsArr?.length) {
        // eslint-disable-next-line array-callback-return
        this.dynamicControlsArr.map(item => {
          if (item.ComponentName && item.ComponentType && item.ChannelComponentId) {
            this.$set(this.stepTwoForm, item.ComponentName, '');
          }
        });
      }
    },


  },
};
</script>

<style lang="scss" scoped>
.contract-create {
  position: relative;
  padding: 0 10px;
  .steps-content {
    position: relative;
    margin-top: 30px;
    .el-form .el-form-item .el-form-item__content {
      .el-input, .el-select {
        width: 260px;
      }
    }

    .form-btns {
      text-align: right;
      margin-bottom: 0;
      margin-top: 40px;
    }

    .contract-preview {
      position: relative;
      width: 100%;
      &.preview-loading:after {
        content: '';
        position: absolute;
        top: 40%;
        left: 50%;
        width: 40px;
        height: 40px;
        margin-left: -20px;
        border-radius: 50%;
        border: 2px solid transparent;
        border-top: 2px solid #409eff;
        border-left: 2px solid #409eff;
        border-right: 2px solid #409eff;
        animation: rotate 1s infinite linear;
        z-index: 0;
      }
      .ifram-wrapper {
        position: relative;
        top: 0;
        width: 100%;
        height: 560px;
        z-index: 1;
      }
      .form-btns {
        margin-top: 20px;
      }
    }
  }
}
@keyframes rotate {
  100% {
    transform: rotate(360deg);
  }
}
</style>
